package com.gsm.common.comtroller;

import com.gsm.domain.system.resp.ProfileResult;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: java类作用描述
 * @Author: gaoshengmin
 * @CreateDate: 2020/2/8$ 14:28$
 * @UpdateUser: gaoshengmin
 * @UpdateDate: 2020/2/8$ 14:28$
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
public class BaseController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected String companyId;
    protected String companyName;

    //使用JWT 方式获取
//    @ModelAttribute  //执行控制器之前，会先执行这个方法
//    public void setResAnReq(HttpServletRequest request , HttpServletResponse response){
//        this.request = request;
//        this.response = response;
//        this.companyId = "1";
//        this.companyName = "GSM";
//        Object obj = request.getAttribute("user_claims");
//        if (StringUtils.isEmpty(obj) && obj instanceof Claims){
//            this.claims = (Claims) obj;
//            this.companyId = (String)claims.get("companyId");
//            this.companyName = (String)claims.get("companyName");
//        }
//    }

    @ModelAttribute  //执行控制器之前，会先执行这个方法
    public void setResAnReq(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        Subject subject = SecurityUtils.getSubject();
        //1.获取Subject的所有安全数据集合
        PrincipalCollection principals = subject.getPrincipals();

        if (!StringUtils.isEmpty(principals)) {
            ProfileResult result = (ProfileResult) principals.getPrimaryPrincipal();
            this.companyId = result.getCompanyId();
            this.companyName = result.getCompany();
        }
    }
}
